package com.xnyzc.lhy.order.service.impl.order;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xnyzc.lhy.common.component.amap.GouldMapUtils;
import com.xnyzc.lhy.common.component.config.GlobalConfig;
import com.xnyzc.lhy.common.component.redis.RedisCommon;
import com.xnyzc.lhy.common.constant.MessageConstant;
import com.xnyzc.lhy.common.constant.MqConstant;
import com.xnyzc.lhy.common.constant.RedisPrefixConstant;
import com.xnyzc.lhy.common.entity.*;
import com.xnyzc.lhy.common.entity.order.OaDOrderCharteredDetail;
import com.xnyzc.lhy.common.exception.DiDiException;
import com.xnyzc.lhy.common.exception.PangException;
import com.xnyzc.lhy.common.global.Configuration;
import com.xnyzc.lhy.common.penum.EDiDiErrorCode;
import com.xnyzc.lhy.common.penum.EErrorCode;
import com.xnyzc.lhy.common.penum.EOrderType;
import com.xnyzc.lhy.common.penum.client.ESystemType;
import com.xnyzc.lhy.common.penum.gould.EGould;
import com.xnyzc.lhy.common.penum.order.*;
import com.xnyzc.lhy.common.penum.star.EStarType;
import com.xnyzc.lhy.common.penum.vehicle.EvehicleType;
import com.xnyzc.lhy.common.util.CheckUtil;
import com.xnyzc.lhy.common.util.DateUtil;
import com.xnyzc.lhy.common.util.EmptyUtil;
import com.xnyzc.lhy.common.util.TokenUtil;
import com.xnyzc.lhy.mis.entity.system.CharterRulesParam;
import com.xnyzc.lhy.mis.entity.system.OaSysBillRule;
import com.xnyzc.lhy.mis.entity.system.OaSysBillRules;
import com.xnyzc.lhy.order.common.constants.BillConstant;
import com.xnyzc.lhy.order.common.constants.OrderStatusConstant;
import com.xnyzc.lhy.order.entity.bill.OaDBill;
import com.xnyzc.lhy.order.entity.common.order.OrderCommon;
import com.xnyzc.lhy.order.entity.dictionaries.OaSysDict;
import com.xnyzc.lhy.order.entity.driver.wallet.OaDWallet;
import com.xnyzc.lhy.order.entity.order.*;
import com.xnyzc.lhy.order.entity.param.cms.PageDto;
import com.xnyzc.lhy.order.entity.param.order.CharteredOrderInfoParam;
import com.xnyzc.lhy.order.entity.param.order.DOrderDetailsResults;
import com.xnyzc.lhy.order.entity.param.order.PassengersOrderResults;
import com.xnyzc.lhy.order.entity.param.synchronization.StatusCallbackParam;
import com.xnyzc.lhy.order.entity.result.order.OrderBillDetailResults;
import com.xnyzc.lhy.order.entity.system.OaSysGlobalConfig;
import com.xnyzc.lhy.order.entity.user.OaDUser;
import com.xnyzc.lhy.order.entity.user.OaDUserInfo;
import com.xnyzc.lhy.order.entity.user.message.OaSysMessage;
import com.xnyzc.lhy.order.feign.amap.IAmapService;
import com.xnyzc.lhy.order.feign.didi.IDidiService;
import com.xnyzc.lhy.order.feign.fallback.finance.OaDFreezeServiceFallback;
import com.xnyzc.lhy.order.feign.push.FeignMessageSendService;
import com.xnyzc.lhy.order.feign.statistics.FeignTrajectoryService;
import com.xnyzc.lhy.order.mapper.bill.OaDBillMapper;
import com.xnyzc.lhy.order.mapper.dictionaries.OaSysDictMapper;
import com.xnyzc.lhy.order.mapper.driver.wallet.OaDWalletMapper;
import com.xnyzc.lhy.order.mapper.order.*;
import com.xnyzc.lhy.order.mapper.system.OaSysBillRuleMapper;
import com.xnyzc.lhy.order.mapper.system.OaSysBillRulesMapper;
import com.xnyzc.lhy.order.mapper.system.OaSysGlobalConfigMapper;
import com.xnyzc.lhy.order.mapper.user.OaDUserInfoMapper;
import com.xnyzc.lhy.order.mq.MqOrderProducer;
import com.xnyzc.lhy.order.service.comment.IOaSysCommentService;
import com.xnyzc.lhy.order.service.driver.IOaDUserInfoService;
import com.xnyzc.lhy.order.service.impl.work.OaDWorkStatisticsServiceImpl;
import com.xnyzc.lhy.order.service.order.IOaDOrderCorrelationService;
import com.xnyzc.lhy.order.service.user.message.IOaSysMessageService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * <p>
 * 司机接单表 服务实现类
 * </p>
 *
 * @author huxuekuo
 * @since 2019-07-19
 */
@Service
@Slf4j
public class OaDOrderCorrelationServiceImpl extends ServiceImpl<OaDOrderMapper, OaDOrder> implements IOaDOrderCorrelationService {

    private final Integer GET_IMAGE_FILED = 111;
    @Autowired
    IDidiService iDidiService;
    @Autowired
    private IOaDUserInfoService dUserInfoService;
    @Autowired
    private RedisCommon redisCommon;
    @Autowired
    private OrderCommon common;
    @Autowired
    private IOaSysMessageService iOaSysMessageService;
    @Autowired
    private MqOrderProducer producer;
    /**
     * 司机订单Mapper
     */
    @Autowired
    private OaDOrderMapper oaDOrderMapper;
    @Autowired
    private OaDOrderServiceImpl oaDOrderService;
    /**
     * 订单评价表Mapper
     */
    @Autowired
    private OaOrderEvaluationMapper oaOrderEvaluationMapper;

    /**
     * 叫车审批Mapper
     */
    @Autowired
    private OaCOrderApprovalOfficialMapper oaCOrderApprovalOfficialMapper;

    /**
     * 部门公务Mapper
     */
    @Autowired
    private OaCOrderDeptOfficialMapper oaCOrderDeptOfficialMapper;

    /**
     * 自费叫车Mapper
     */
    @Autowired
    private OaCOrderPersonalMapper oaCOrderPersonalMapper;

    /**
     * 个人公务Mapper
     */
    @Autowired
    private OaCOrderPersonalOfficialMapper oaCOrderPersonalOfficialMapper;

    /**
     * 订单状态字典Mapper
     */
    @Autowired
    private OaSysDictMapper oaSysDictMapper;

    @Autowired
    private OaDBillMapper oaDBillMapper;

    /**
     * 引用方法
     */
    @Autowired
    private IOaSysCommentService iOaSysCommentService;

    /**
     * 轨迹查询服务
     */
    @Autowired
    private FeignTrajectoryService feignTrajectoryService;


    /**
     * 地图服务
     */
    @Autowired
    private IAmapService iAmapService;

    @Autowired
    private OaSysBillRulesMapper oaSysBillRulesMapper;

    @Autowired
    private OaSysBillRuleMapper oaSysBillRuleMapper;

    @Autowired
    private OaDUserInfoMapper oaDUserInfoMapper;

    @Autowired
    private OaSysGlobalConfigMapper oaSysGlobalConfigMapper;
    /**
     * 图片服务
     */
    @Autowired
    private FeignMessageSendService feignMessageSendService;
    @Autowired
    private OaOrderOtherPriceMapper oaOrderOtherPriceMapper;
    /**
     * 司机钱包
     */
    @Autowired
    private OaDWalletMapper oaDWalletMapper;
    /**
     * 包车业务
     */
    @Autowired
    private OaDOrderCharterDetailMapper oaDOrderCharterDetailMapper;
    @Autowired
    private OaDWorkStatisticsServiceImpl oaDWorkStatisticsServiceImpl;
    @Autowired
    private OaDFreezeServiceFallback oaDFreezeServiceFallback;

    /**
     * 订单列表
     *
     * @param userId 司机用户ID
     * @param type   订单类型
     * @param page   页码
     * @return
     */
    @Override
    public Rv dOrderList(Long userId, String type, Integer page) {
        //必填验证
        //type 全部:all 未支付:arrearage 已取消:cancel
        if (StringUtils.isBlank(type) || CheckUtil.objIsEmpty(page)) {
            throw PangException.create(EErrorCode.noData);
        }
        //查询用车类型字典
        List<OaSysDict> orderLevelDictList = getOrderLevelDict();
        if (EmptyUtil.isEmpty(orderLevelDictList)) {
            throw PangException.create(EErrorCode.noData);
        }
        // 查询审批订单
        List<OaCOrderApprovalOfficial> approvalOfficialList = getOrderApprovalOfficialByDriverId(userId, type);
        // 查询个人公务订单
        List<OaCOrderPersonalOfficial> personalOfficialList = getOrderPersonalOfficialByDriverId(userId, type);
        // 查询自费叫车订单
        List<OaCOrderPersonal> personalList = getOrderPersonalByDriverId(userId, type);
        // 查询部门公务订单
        List<OaCOrderDeptOfficial> deptOfficialList = getOrderDeptByDriverId(userId, type);
        List<PassengersOrderResults> collectList = new ArrayList<>();
        collectList = getDataMerge(collectList, approvalOfficialList, personalOfficialList, personalList, deptOfficialList);
        List<PassengersOrderResults> resultsList = new ArrayList<>();
        if (EmptyUtil.isEmpty(collectList)) {
            return Rv.wrap(EErrorCode.success, resultsList);
        } else {
            // 遍历车型
            for (PassengersOrderResults collect : collectList) {
                for (OaSysDict level : orderLevelDictList) {
                    if (collect.getVehicleType().equals(Integer.valueOf(level.getValue()))) {
                        collect.setVehicleTypeStr(level.getLabel());
                    }
                }
            }
        }
        //数据处理
        resultsList = getOrderDataProcessing(collectList, page);
        return Rv.wrap(EErrorCode.success, resultsList);
    }


    public List<PassengersOrderResults> getDataMerge(List<PassengersOrderResults> collectList, List<OaCOrderApprovalOfficial> approvalOfficialList, List<OaCOrderPersonalOfficial> personalOfficialList,
                                                     List<OaCOrderPersonal> personalList, List<OaCOrderDeptOfficial> deptOfficialList) {
        PassengersOrderResults result = new PassengersOrderResults();
        // 审批订单
        if (!EmptyUtil.isEmpty(approvalOfficialList)) {
            for (OaCOrderApprovalOfficial official : approvalOfficialList) {
                result = new PassengersOrderResults();
                result.setVehicleType(official.getVehicleType());
                result.setId(official.getApprovalOfficialId());
                result.setIsCarpool(0);
                result.setPassengerPhone("");
                if (StringUtils.isNotEmpty(official.getPassengerPhone())) {
                    String phone = official.getPassengerPhone().substring(official.getPassengerPhone().length() - 4, official.getPassengerPhone().length());
                    result.setPassengerPhone(phone);
                }
                result.setTitle(MessageConstant.AUDITOFFICIAL);
                result.setOrderNo(official.getOrderNo());
                result.setEndAddress(official.getEndAddress());
                result.setOrderStatus(official.getOrderStatus());
                result.setOrderTime(getDateConversion(official.getOrderTime()));
                result.setOrderType(official.getOrderType());
                result.setStartAddress(official.getStartAddress());
                collectList.add(result);
            }
        }
        // 部门公务订单
        if (!EmptyUtil.isEmpty(deptOfficialList)) {
            for (OaCOrderDeptOfficial official : deptOfficialList) {
                result = new PassengersOrderResults();
                result.setIsCarpool(0);
                result.setVehicleType(official.getVehicleType());
                result.setPassengerPhone("");
                if (StringUtils.isNotEmpty(official.getPassengerPhone())) {
                    String phone = official.getPassengerPhone().substring(official.getPassengerPhone().length() - 4, official.getPassengerPhone().length());
                    result.setPassengerPhone(phone);
                }
                result.setTitle(MessageConstant.DEPTOFFICIAL);
                result.setOrderNo(official.getOrderNo());
                result.setEndAddress(official.getEndAddress());
                result.setOrderStatus(official.getOrderStatus());
                result.setOrderTime(getDateConversion(official.getOrderTime()));
                result.setOrderType(official.getOrderType());
                result.setStartAddress(official.getStartAddress());
                collectList.add(result);
            }
        }
        //查询自费叫车订单
        if (!EmptyUtil.isEmpty(personalList)) {
            for (OaCOrderPersonal personal : personalList) {
                result = new PassengersOrderResults();
                result.setVehicleType(personal.getVehicleType());
                result.setTitle(MessageConstant.PERSONALCALL);
                result.setOrderNo(personal.getOrderNo());
                result.setEndAddress(personal.getEndAddress());
                result.setOrderStatus(personal.getOrderStatus());
                result.setOrderTime(getDateConversion(personal.getOrderTime()));
                result.setOrderType(personal.getOrderType());
                result.setStartAddress(personal.getStartAddress());
                result.setIsCarpool(personal.getIsCarpool());
                result.setPassengerPhone("");
                if (StringUtils.isNotEmpty(personal.getPassengerPhone())) {
                    String phone = personal.getPassengerPhone().substring(personal.getPassengerPhone().length() - 4, personal.getPassengerPhone().length());
                    result.setPassengerPhone(phone);
                }
                collectList.add(result);
            }
        }
        //查询个人公务订单
        if (!EmptyUtil.isEmpty(personalOfficialList)) {
            for (OaCOrderPersonalOfficial official : personalOfficialList) {
                result = new PassengersOrderResults();
                result.setIsCarpool(0);
                result.setVehicleType(official.getVehicleType());
                result.setPassengerPhone("");
                if (StringUtils.isNotEmpty(official.getPassengerPhone())) {
                    String phone = official.getPassengerPhone().substring(official.getPassengerPhone().length() - 4, official.getPassengerPhone().length());
                    result.setPassengerPhone(phone);
                }
                result.setTitle(MessageConstant.PERSONALOFFICIAL);
                result.setOrderNo(official.getOrderNo());
                result.setEndAddress(official.getEndAddress());
                result.setOrderStatus(official.getOrderStatus());
                result.setOrderTime(getDateConversion(official.getOrderTime()));
                result.setOrderType(official.getOrderType());
                result.setStartAddress(official.getStartAddress());
                collectList.add(result);
            }
        }
        return collectList;
    }

    /**
     * 通过userId查询审批公务订单
     *
     * @param userId
     * @return
     */
    private List<OaCOrderApprovalOfficial> getOrderApprovalOfficialByDriverId(Long userId, String type) {
        QueryWrapper<OaCOrderApprovalOfficial> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(OaCOrderApprovalOfficial.DRIVER_ID, userId);
        if (type.equals(GlobalConfig.ARREARAGE)) {
            // 未支付
            List<Integer> status = new ArrayList<>();
            status.add(EOrderStatus.normalOrderPendingPayment.getType());
            status.add(EOrderStatus.cancelOrdersFeesPaid.getType());
            queryWrapper.in(OaCOrderApprovalOfficial.ORDER_STATUS, status);
        } else if (type.equals(GlobalConfig.CANCEL)) {
            // 已取消
            List<Integer> status = new ArrayList<>();
            status.add(EOrderStatus.cancelOrderNoNeedPayment.getType());
            status.add(EOrderStatus.abnormalEndOrder.getType());
            queryWrapper.in(OaCOrderApprovalOfficial.ORDER_STATUS, status);
        } else if (type.equals(GlobalConfig.ALL)) {
            // 全部
            List<Integer> status = new ArrayList<>();
            status.add(EOrderStatus.cancelOrderNoNeedPayment.getType());
            status.add(EOrderStatus.abnormalEndOrder.getType());
            queryWrapper.notIn(OaCOrderApprovalOfficial.ORDER_STATUS, status);
        }
        List<OaCOrderApprovalOfficial> approvalOfficialList = oaCOrderApprovalOfficialMapper.selectList(queryWrapper);
        return approvalOfficialList;
    }

    /**
     * 通过userId查询部门公务订单
     *
     * @param userId
     * @return
     */
    private List<OaCOrderDeptOfficial> getOrderDeptByDriverId(Long userId, String type) {
        QueryWrapper<OaCOrderDeptOfficial> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(OaCOrderDeptOfficial.DRIVER_ID, userId);
        if (type.equals(GlobalConfig.ARREARAGE)) {
            List<Integer> status = new ArrayList<>();
            status.add(EOrderStatus.normalOrderPendingPayment.getType());
            status.add(EOrderStatus.cancelOrdersFeesPaid.getType());
            // 未支付
            queryWrapper.in(OaCOrderDeptOfficial.ORDER_STATUS, status);
        } else if (type.equals(GlobalConfig.CANCEL)) {
            List<Integer> status = new ArrayList<>();
            status.add(EOrderStatus.cancelOrderNoNeedPayment.getType());
            status.add(EOrderStatus.abnormalEndOrder.getType());
            queryWrapper.in(OaCOrderDeptOfficial.ORDER_STATUS, status);
        } else if (type.equals(GlobalConfig.ALL)) {
            // 全部
            List<Integer> status = new ArrayList<>();
            status.add(EOrderStatus.cancelOrderNoNeedPayment.getType());
            status.add(EOrderStatus.abnormalEndOrder.getType());
            queryWrapper.notIn(OaCOrderDeptOfficial.ORDER_STATUS, status);
        }
        List<OaCOrderDeptOfficial> deptOfficialList = oaCOrderDeptOfficialMapper.selectList(queryWrapper);
        return deptOfficialList;
    }

    /**
     * 通过userId查询自费叫车订单
     *
     * @param userId
     * @return
     */
    private List<OaCOrderPersonal> getOrderPersonalByDriverId(Long userId, String type) {
        QueryWrapper<OaCOrderPersonal> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(OaCOrderPersonal.DRIVER_ID, userId);
        if (type.equals(GlobalConfig.ARREARAGE)) {
            // 未支付
            List<Integer> status = new ArrayList<>();
            status.add(EOrderStatus.normalOrderPendingPayment.getType());
            status.add(EOrderStatus.cancelOrdersFeesPaid.getType());
            queryWrapper.in(OaCOrderPersonal.ORDER_STATUS, status);
        } else if (type.equals(GlobalConfig.CANCEL)) {
            // 已取消
            List<Integer> status = new ArrayList<>();
            status.add(EOrderStatus.cancelOrderNoNeedPayment.getType());
            status.add(EOrderStatus.abnormalEndOrder.getType());
            queryWrapper.in(OaCOrderPersonal.ORDER_STATUS, status);
        } else if (type.equals(GlobalConfig.ALL)) {
            // 全部
            List<Integer> status = new ArrayList<>();
            status.add(EOrderStatus.cancelOrderNoNeedPayment.getType());
            status.add(EOrderStatus.abnormalEndOrder.getType());
            queryWrapper.notIn(OaCOrderPersonal.ORDER_STATUS, status);
        }
        List<OaCOrderPersonal> personalList = oaCOrderPersonalMapper.selectList(queryWrapper);
        return personalList;
    }

    /**
     * 通过userId查询个人公务订单
     *
     * @param userId
     * @return
     */
    private List<OaCOrderPersonalOfficial> getOrderPersonalOfficialByDriverId(Long userId, String type) {
        QueryWrapper<OaCOrderPersonalOfficial> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(OaCOrderPersonalOfficial.DRIVER_ID, userId);
        if (type.equals(GlobalConfig.ARREARAGE)) {
            // 未支付
            List<Integer> status = new ArrayList<>();
            status.add(EOrderStatus.normalOrderPendingPayment.getType());
            status.add(EOrderStatus.cancelOrdersFeesPaid.getType());
            queryWrapper.in(OaCOrderPersonalOfficial.ORDER_STATUS, status);
        } else if (type.equals(GlobalConfig.CANCEL)) {
            // 已取消
            List<Integer> status = new ArrayList<>();
            status.add(EOrderStatus.cancelOrderNoNeedPayment.getType());
            status.add(EOrderStatus.abnormalEndOrder.getType());
            queryWrapper.ne(OaCOrderPersonalOfficial.ORDER_STATUS, status);
        } else if (type.equals(GlobalConfig.ALL)) {
            // 全部
            List<Integer> status = new ArrayList<>();
            status.add(EOrderStatus.cancelOrderNoNeedPayment.getType());
            status.add(EOrderStatus.abnormalEndOrder.getType());
            queryWrapper.notIn(OaCOrderPersonalOfficial.ORDER_STATUS, status);
        }
        List<OaCOrderPersonalOfficial> personalOfficialList = oaCOrderPersonalOfficialMapper.selectList(queryWrapper);
        return personalOfficialList;
    }

    /**
     * Date转String
     *
     * @param date
     * @return
     */
    public String getDateConversion(Date date) {
        String time = "";
        if (CheckUtil.objIsEmpty(date)) {
            return time;
        }
        Instant instant = date.toInstant();
        ZoneId zone = ZoneId.systemDefault();
        LocalDateTime localTime = LocalDateTime.ofInstant(instant, zone);
        DateTimeFormatter formater = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        time = formater.format(localTime);
        return time;
    }

    /**
     * 查询订单状态字典表
     *
     * @return
     */
    private List<OaSysDict> getOrderDict() {
        QueryWrapper<OaSysDict> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(OaSysDict.TYPE, "order_status");
        List<OaSysDict> orderDictList = oaSysDictMapper.selectList(queryWrapper);
        return orderDictList;
    }

    /**
     * 查询车型字典表
     *
     * @return
     */
    private List<OaSysDict> getOrderLevelDict() {
        QueryWrapper<OaSysDict> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(OaSysDict.TYPE, "require_level");
        List<OaSysDict> orderDictList = oaSysDictMapper.selectList(queryWrapper);
        return orderDictList;
    }

    /**
     * 订单列表数据处理
     *
     * @return
     */
    public List<PassengersOrderResults> getOrderDataProcessing(List<PassengersOrderResults> collectList, Integer page) {
        for (PassengersOrderResults results : collectList) {
            // 0、3、4、5、6、13、14行程中 7、9待支付 10、11已取消 12已支付 15审核通过
            if (results.getOrderStatus().equals(EOrderStatus.waitingResponse.getType()) ||
                    results.getOrderStatus().equals(EOrderStatus.driverOrder.getType()) ||
                    results.getOrderStatus().equals(EOrderStatus.reservationLocation.getType()) ||
                    results.getOrderStatus().equals(EOrderStatus.driverArrived.getType()) ||
                    results.getOrderStatus().equals(EOrderStatus.duringTrip.getType()) ||
                    results.getOrderStatus().equals(EOrderStatus.privateItinerary.getType()) ||
                    results.getOrderStatus().equals(EOrderStatus.sendBill.getType())) {
                results.setOrderStatusStr(MessageConstant.THETRIP);
            } else if (results.getOrderStatus().equals(EOrderStatus.normalOrderPendingPayment.getType()) ||
                    results.getOrderStatus().equals(EOrderStatus.cancelOrdersFeesPaid.getType())) {
                results.setOrderStatusStr(MessageConstant.UNPAID);
            } else if (results.getOrderStatus().equals(EOrderStatus.cancelOrderNoNeedPayment.getType()) ||
                    results.getOrderStatus().equals(EOrderStatus.abnormalEndOrder.getType())) {
                results.setOrderStatusStr(MessageConstant.CANCELED);
            } else if (results.getOrderStatus().equals(EOrderStatus.paymented.getType())) {
                results.setOrderStatusStr(MessageConstant.HAVEPAY);
            } else if (results.getOrderStatus().equals(EOrderStatus.examination.getType())) {
                results.setOrderStatusStr(MessageConstant.APPROVED);
            }
        }
        List<PassengersOrderResults> list = getSort(collectList, page);
        return list;
    }

    /**
     * 排序
     *
     * @param collectList
     * @param page
     * @return
     */
    public List<PassengersOrderResults> getSort(List<PassengersOrderResults> collectList, Integer page) {
        Collections.sort(collectList, new Comparator() {
            @Override
            public int compare(Object o1, Object o2) {
                PassengersOrderResults w1 = (PassengersOrderResults) o1;
                PassengersOrderResults w2 = (PassengersOrderResults) o2;
                return w2.getOrderTime().compareTo(w1.getOrderTime());
            }
        });
        Integer pageSize = Configuration.pageSize;
        if (collectList.size() >= pageSize * (page)) {
            collectList = collectList.subList(pageSize * (page - 1), pageSize * (page));
        } else {
            if (collectList.size() >= pageSize * (page - 1)) {
                collectList = collectList.subList(pageSize * (page - 1), collectList.size());
            } else {
                List<PassengersOrderResults> list = new ArrayList<>();
                return list;
            }
        }
        return collectList;
    }

    /**
     * 司机端订单详情
     *
     * @param orderNo
     * @return
     */
    @Override
    public Rv dOrderDetails(String orderNo, String userType, String tag) {
        //必填验证
        if (StringUtils.isBlank(orderNo)) {
            throw PangException.create(EErrorCode.noData);
        }
        //返回参数
        List<DOrderDetailsResults> resultsList = new ArrayList<>();
        DOrderDetailsResults results = new DOrderDetailsResults();
        //查询订单状态字典
        List<OaSysDict> orderDictList = getOrderDict();
        if (EmptyUtil.isEmpty(orderDictList)) {
            throw PangException.create(EErrorCode.noData);
        }
        Long userOrderNo = 0L;
        //审批公务订单
        if (orderNo.contains(EOrderType.SPGW.getValue())) {
            OaCOrderApprovalOfficial official = getOrderApprovalOfficialByOrder(orderNo);
            userOrderNo = official.getApprovalOfficialId();
            results.setStartAddress(official.getStartAddress());
            results.setEndAddress(official.getEndAddress());
            OaOrderEvaluation orderEvaluation = getOrderEvaluation(userOrderNo);
            if (CheckUtil.objIsEmpty(orderEvaluation)) {
                results.setStar("");
            } else {
                results.setStar(orderEvaluation.getEvaluationScore());
            }
            results.setOrderStatus(official.getOrderStatus());
            String orderStatusStr = getOrderStatus(official.getOrderStatus(), orderDictList);
            results.setOrderStatusStr(orderStatusStr);
        } else if (orderNo.contains(EOrderType.BMGW.getValue())) {
            //部门公务订单
            OaCOrderDeptOfficial official = getOrderDeptByOrderNo(orderNo);
            userOrderNo = official.getDeptOfficialId();
            results.setStartAddress(official.getStartAddress());
            results.setEndAddress(official.getEndAddress());
            OaOrderEvaluation orderEvaluation = getOrderEvaluation(userOrderNo);
            if (CheckUtil.objIsEmpty(orderEvaluation)) {
                results.setStar("");
            } else {
                results.setStar(orderEvaluation.getEvaluationScore());
            }
            results.setOrderStatus(official.getOrderStatus());
            String orderStatusStr = getOrderStatus(official.getOrderStatus(), orderDictList);
            results.setOrderStatusStr(orderStatusStr);
        } else if (orderNo.contains(EOrderType.ZFJC.getValue())) {
            //自费
            OaCOrderPersonal official = getOrderPersonalByOrderNo(orderNo);
            userOrderNo = official.getPersonalId();
            results.setStartAddress(official.getStartAddress());
            results.setEndAddress(official.getEndAddress());
            OaOrderEvaluation orderEvaluation = getOrderEvaluation(userOrderNo);
            if (CheckUtil.objIsEmpty(orderEvaluation)) {
                results.setStar("");
            } else {
                results.setStar(orderEvaluation.getEvaluationScore());
            }
            results.setOrderStatus(official.getOrderStatus());
            String orderStatusStr = getOrderStatus(official.getOrderStatus(), orderDictList);
            results.setOrderStatusStr(orderStatusStr);
        } else if (orderNo.contains(EOrderType.GRGW.getValue())) {
            OaCOrderPersonalOfficial official = getOrderPersonalOfficialByOrderNo(orderNo);
            userOrderNo = official.getPersonalOfficialId();
            results.setStartAddress(official.getStartAddress());
            results.setEndAddress(official.getEndAddress());
            OaOrderEvaluation orderEvaluation = getOrderEvaluation(userOrderNo);
            if (CheckUtil.objIsEmpty(orderEvaluation)) {
                results.setStar("");
            } else {
                results.setStar(orderEvaluation.getEvaluationScore());
            }
            results.setOrderStatus(official.getOrderStatus());
            String orderStatusStr = getOrderStatus(official.getOrderStatus(), orderDictList);
            results.setOrderStatusStr(orderStatusStr);
        }
        // 数据整理
        getDOrderResults(results, userOrderNo, userType, tag);
        return Rv.wrap(EErrorCode.success, results);
    }

    /**
     * 获取司机行程列表
     *
     * @param driverId 司机ID
     * @param pageDto  分页
     * @return
     */
    @Override
    public Rv getDriverOrder(Long driverId, PageDto pageDto) {
        if (CheckUtil.objIsEmpty(pageDto.getLimit())) {
            // 若没有则默认显示十页
            pageDto.setLimit(10L);
        }
        if (CheckUtil.objIsEmpty(pageDto.getPage()) || CheckUtil.objIsEmpty(pageDto.getLimit())
                || CheckUtil.objIsEmpty(pageDto.getOrderStatus())) {
            throw PangException.create(EErrorCode.missingArg);
        }

        List<Map<String, Object>> mapList = oaDOrderMapper.queryDriverOrder(driverId, pageDto.getOrderStatus(), pageDto.getIndex(), pageDto.getLimit());
        return Rv.wrap(mapList);
    }

    /**
     * 司机端改派请求
     *
     * @param driverId
     * @param orderNo
     * @return
     */
    @Override
    public Rv getDriverReassignmentOrder(Long driverId, String orderNo) {
        if (CheckUtil.objIsEmpty(orderNo)) {
            throw PangException.create(EErrorCode.missingArg);
        }
        //查询司机订单
        QueryWrapper<OaDOrder> oaDOrderQueryWrapper = new QueryWrapper<>();
        oaDOrderQueryWrapper.eq(OaDOrder.DRIVER_ID, driverId);
        oaDOrderQueryWrapper.eq(OaDOrder.ORDER_NO, orderNo);
        OaDOrder oaDOrder = oaDOrderMapper.selectOne(oaDOrderQueryWrapper);
        if (CheckUtil.objIsEmpty(oaDOrder)) {
            throw PangException.create(EErrorCode.unData);
        }
        //查询乘客订单
        QueryWrapper<OaCOrderPersonal> orderPersonalQueryWrapper = new QueryWrapper<>();
        orderPersonalQueryWrapper.eq(OaCOrderPersonal.ORDER_NO, orderNo);
        OaCOrderPersonal oaCOrderPersonal = oaCOrderPersonalMapper.selectOne(orderPersonalQueryWrapper);
        if (CheckUtil.objIsEmpty(oaCOrderPersonal)) {
            throw PangException.create(EErrorCode.unData);
        }
        //修改乘客订单
        oaCOrderPersonal.setDriverId(null);
        oaCOrderPersonal.setOrderStatus(EOrderStatus.changeDriver.getType());//设置司机改派状态
        //更新乘客订单
        int isUpdate = oaCOrderPersonalMapper.updateById(oaCOrderPersonal);
        //删除原来司机订单的信息
        int isDelete = oaDOrderMapper.delete(oaDOrderQueryWrapper);
        if (isUpdate < 1 || isDelete < 1) {//验证
            throw PangException.create(EErrorCode.updateWalletFailure);
        }
        //司机扣除改派费根据城市信息,订单渠道和订单号获取相关信息
        String cityId = oaCOrderPersonal.getCityId();
        Integer orderChannel = oaCOrderPersonal.getOrderChannel();
        QueryWrapper<OaDWallet> oaDWalletQueryWrapper = new QueryWrapper<>();
        oaDWalletQueryWrapper.eq(OaDWallet.DRIVER_ID, driverId);
        OaDWallet oaDWallet = oaDWalletMapper.selectOne(oaDWalletQueryWrapper);
        if (CheckUtil.objIsEmpty(oaDWallet)) {
            throw PangException.create(EErrorCode.unData);
        }
        //司机钱包余额
        BigDecimal walletBalance = oaDWallet.getWalletBalance();
        //减去改派费用
        walletBalance.subtract(BigDecimal.valueOf(0));//修改金额

        oaDWallet.setWalletBalance(walletBalance);
        //更新司机钱包余额
        int isUpdate2 = oaDWalletMapper.updateById(oaDWallet);
        if (isUpdate2 < 1) {//验证
            throw PangException.create(EErrorCode.updateWalletFailure);
        }
        return Rv.wrap();
    }

    /**
     * 获取司机预约行程列表
     *
     * @param driverId 司机ID
     * @param pageDto  分页
     * @return
     */
    @Override
    public Rv getDriverBookingOrder(Long driverId, PageDto pageDto) {
        if (CheckUtil.objIsEmpty(pageDto.getLimit())) {
            // 若没有则默认显示十页
            pageDto.setLimit(10L);
        }
        if (CheckUtil.objIsEmpty(pageDto.getPage()) || CheckUtil.objIsEmpty(pageDto.getLimit())) {
            throw PangException.create(EErrorCode.missingArg);
        }

        EOrderStatus status = EOrderStatus.driverOrder;
        List<Map<String, Object>> mapList = oaDOrderMapper.queryDriverBookingOrder(driverId, status.getType(), pageDto.getIndex(), pageDto.getLimit());
        return Rv.wrap(mapList);
    }

    /**
     * 获取司机行程详情
     *
     * @param orderNo 订单ID
     * @return
     */
    @Override
    public Rv getOrderInfo(String orderNo,Date appointmentTime) {
        Map<String, Object> map = oaDOrderMapper.queryOrderInfo(orderNo,appointmentTime);
        int orderStatus = (Integer) map.get("orderStatus");
        map.put("totalCost", map.get("totalCost").toString() + "元");
        map.put("titleText", "");
        if (
                orderStatus == EOrderStatus.normalOrderPendingPayment.getType() ||
                        orderStatus == EOrderStatus.paymented.getType()
        ) {
            map.put("orderStatus", 2);
            if (CheckUtil.objIsNotEmpty(map.get("startAddressName"))) {
                map.put("actualStartName", map.get("startAddressName"));
                map.put("actualFlat", map.get("startLat"));
                map.put("actualFlng", map.get("startLng"));
            }
            if (CheckUtil.objIsNotEmpty(map.get("endAddressName"))) {
                map.put("actualEndName", map.get("endAddressName"));
                map.put("actualTlat", map.get("endLat"));
                map.put("actualTlng", map.get("endLng"));
            }
        } else if (orderStatus == OrderStatusConstant.WAIT_APPLY_AMOUNT) {
            map.put("orderStatus", 3);
            if (CheckUtil.objIsNotEmpty(map.get("startAddressName"))) {
                map.put("actualStartName", map.get("startAddressName"));
                map.put("actualFlat", map.get("startLat"));
                map.put("actualFlng", map.get("startLng"));
            }
            if (CheckUtil.objIsNotEmpty(map.get("endAddressName"))) {
                map.put("actualEndName", map.get("endAddressName"));
                map.put("actualTlat", map.get("endLat"));
                map.put("actualTlng", map.get("endLng"));
            }
        } else if (
                orderStatus == EOrderStatus.reassigned.getType() ||
                        orderStatus == EOrderStatus.serviceClose.getType() ||
                        orderStatus == EOrderStatus.driverCancelOrder.getType() ||
                        orderStatus == EOrderStatus.cancelPendingPayment.getType() ||
                        orderStatus == EOrderStatus.cancelOrdersFeesPaid.getType() ||
                        orderStatus == EOrderStatus.cancelOrderNoNeedPayment.getType() ||
                        orderStatus == EOrderStatus.abnormalEndOrder.getType()
        ) {
            map.put("orderStatus", 1);
        } else if (orderStatus == EOrderStatus.driverThrowOrder.getType()) {
            map.put("orderStatus", 5);
        } else {
            map.put("orderStatus", 0);
            BigDecimal distance = (BigDecimal) map.get(EGould.gouldDistance.getValue());
            BigDecimal duration = (BigDecimal) map.get(EGould.gouldDuration.getValue());
            map.put("titleText", "此次行程预计" + distance.setScale(2, RoundingMode.HALF_UP) + "千米，大约需要" + duration.setScale(0, RoundingMode.HALF_UP) + "分钟");
        }
        map.put("passengerPhone", map.get("passengerPhone"));
        map.put("passengerphonesuffix", map.get("passengerphonesuffix"));
        String driverPhone = map.get("driverPhone").toString();
        driverPhone = driverPhone.substring(driverPhone.length() - 4);
        map.put("driverPhone", MessageConstant.TAILNUMBER + driverPhone);
        // 获取客服电话
        QueryWrapper<OaSysGlobalConfig> oaSysGlobalConfigQueryWrapper = new QueryWrapper<>();
        oaSysGlobalConfigQueryWrapper.select(OaSysGlobalConfig.SERVICE_PHONE);
        List<OaSysGlobalConfig> oaSysGlobalConfigs = null;
        try {
            oaSysGlobalConfigs = oaSysGlobalConfigMapper.selectList(oaSysGlobalConfigQueryWrapper);
        } catch (Exception e) {
            map.put("servicePhone", "");
        }
        if (CheckUtil.collectionIsNotEmpty(oaSysGlobalConfigs)) {
            try {
                map.put("servicePhone", oaSysGlobalConfigs.get(0).getServicePhone());
            } catch (NullPointerException e) {
                map.put("servicePhone", "");
            }
        } else {
            map.put("servicePhone", "");
        }
        if (map.get("passengerPhone") == null) {
            //非待执行订单均不能返回乘客手机号
            map.put("passengerPhone", map.get("servicePhone"));
        }
        if (CheckUtil.objIsEmpty(map.get(OaDUser.AVATAR_FILE_ID))) {
            map.put("avatarFile", "");
        } else {
            Rv rv = feignMessageSendService.getFileUrl((Long) map.get(OaDUser.AVATAR_FILE_ID));
            if (rv.getCode() == GET_IMAGE_FILED) {
                map.put("avatarFile", "");
            } else {
                String fileUrl = ((Map<String, String>) (rv.getData())).get("fileUrl");
                map.put("avatarFile", fileUrl);
            }
        }

        //根据订单类型获取包车相关数据
        if (map.containsKey("orderType") && "7".equals(map.get("orderType").toString())) {
            //查询包车详情表获取起始位置、时间、轨迹id
            QueryWrapper<OaDOrderCharteredDetail> queryWrapper = new QueryWrapper<>();
            //queryWrapper.eq(OaDOrderCharteredDetail.ORDER_DATE, DateUtil.getDateDay());
            queryWrapper.eq(OaDOrderCharteredDetail.ORDER_DATE,appointmentTime);
            queryWrapper.eq(OaDOrderCharteredDetail.ORDER_NO, orderNo);
            OaDOrderCharteredDetail oc = oaDOrderCharterDetailMapper.selectOne(queryWrapper);

            QueryWrapper<OaCOrderPersonal> orderPersonalQueryWrapper = new QueryWrapper<>();
            orderPersonalQueryWrapper.eq(OaCOrderPersonal.ORDER_NO, orderNo);
            OaCOrderPersonal oaCOrderPersonal = oaCOrderPersonalMapper.selectOne(orderPersonalQueryWrapper);
            Long rulesId = oaCOrderPersonal.getRulesId();
            QueryWrapper<OaSysBillRule> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.eq(OaSysBillRule.RULE_ID, rulesId);
            OaSysBillRule oaSysBillRule = oaSysBillRuleMapper.selectOne(queryWrapper1);
            String jsonRules = oaSysBillRule.getJsonRules();
            CharterRulesParam charterRulesParam = JSONObject.parseObject(jsonRules, CharterRulesParam.class);
            String rulesName = oaSysBillRule.getRulesName();
            String[] tmpData = rulesName.split("-");
            String timeLength = tmpData[0];
            String disLength = tmpData[1];
            map.put("orderNo", oc.getOrderNo());
            map.put("realStartTime", oc.getStartTime());//2021-08-16 05:00:00
            map.put("realFlng", oc.getFlng());//103.957128
            map.put("realFlat", oc.getFlat());//30.568311
            map.put("realEndTime", oc.getEndTime());
            map.put("realTlng", oc.getTlng());
            map.put("realTlat", oc.getTlat());
            map.put("trackId", oc.getTrackId());
            //套餐时长
            map.put("timeLength", timeLength);
            //套餐公里
            map.put("disLength", disLength);
            //行驶距离
            map.put("normalDistance", oc.getNormalDistance());
            //行驶时长
            map.put("normalTime", oc.getNormalTime());
            //套餐费
            map.put("packageCost", oc.getPackageCost());//
            //超出里程单价
            map.put("exceedDisPrice", charterRulesParam.getBillRules().getOCMPrice());
            //超出时间单价（1小时）
            map.put("exceedTimePrice", charterRulesParam.getBillRules().getOCDPrice()*2);
            //超时阈值(分钟)
            map.put("exceedTimeThreshold", "5");
            //超出里程
            map.put("exceedDistance", oc.getExceedDistance());
            //超出时间
            map.put("exceedTime", oc.getExceedTime());
            //超出里程费
            map.put("exceedDistanceCost", oc.getExceedDistanceCost());
            //超时费
            map.put("exceedTimeCost", oc.getExceedTimeCost());
            //其他费用
            map.put("otherCost", oc.getOtherCost());
            //其他费用说明
            map.put("otherCostDetail", oc.getOtherCostDetail());
            //乘客支付方式
            map.put("paymentType", oc.getPaymentType());
            map.put("titleText", "套餐信息：" + timeLength + "小时" + disLength + "公里，套餐价格" + map.get("totalCost").toString() + "元。");
        }
        //List<Map<String, Object>> mapList = oaDOrderMapper.queryOrderGps(orderNo);
        map.put("gpsList", new ArrayList<>());
        return Rv.wrap(map);

    }

    /**
     * 包车开始行程
     *
     * @return
     */
    @Override
    public Rv charteredStart(CharteredOrderInfoParam charteredOrderInfoParam, Long driverId) {
        //开始行程，把开始时间/位置/trackID/status存入detail表
        if (charteredOrderInfoParam.getTrackId() == null) {
            return Rv.wrap(EErrorCode.c400, "参数错误");
        }
        String orderNo = charteredOrderInfoParam.getOrderNo();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String dateDay = DateUtil.getDateDay();
        Date date = new Date();
        try {
            date = sdf.parse(dateDay);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        OaDOrderCharteredDetail ot = new OaDOrderCharteredDetail();
        ot.setOrderNo(orderNo);
        ot.setStatus(EOrderStatus.duringTrip.getType());
        ot.setFlat(charteredOrderInfoParam.getFlat());
        ot.setFlng(charteredOrderInfoParam.getFlng());
        ot.setTrackId(charteredOrderInfoParam.getTrackId());
        ot.setStartTime(new Date());
        GouldResult gouldResult = GouldMapUtils.verificationEmbargoArea(charteredOrderInfoParam.getFlng(), charteredOrderInfoParam.getFlat());
        String startAddress = gouldResult.getRegeocode().getFormatted_address();
        ot.setStartAddress(startAddress);
        UpdateWrapper<OaDOrderCharteredDetail> updateWapper = new UpdateWrapper<>();
        updateWapper.eq(OaDOrderCharteredDetail.ORDER_NO, orderNo);
        updateWapper.between(OaDOrderCharteredDetail.ORDER_DATE, DateUtil.getDateDay()+" 00:00:00",DateUtil.getDateDay()+" 23:59:59");
        oaDOrderCharterDetailMapper.update(ot, updateWapper);

        OaDUserInfo oaDUserInfo = new OaDUserInfo();
        oaDUserInfo.setCurrentOrderNo(orderNo);
        UpdateWrapper<OaDUserInfo> oaDUserInfoUpdateWrapper = new UpdateWrapper<>();
        oaDUserInfoUpdateWrapper.eq(OaDUserInfo.DRIVER_ID, driverId);
        oaDUserInfoMapper.updateById(oaDUserInfo);
        Rv rv = oaDWorkStatisticsServiceImpl.startMyBookingOrder(driverId, orderNo, EOrderStatus.duringTrip);
        return rv;
    }

    /**
     * 包车结束行程
     *
     * @param charteredOrderInfoParam
     */
    @Override
    @Transactional
    public Rv charteredEnd(CharteredOrderInfoParam charteredOrderInfoParam, Long driverId) {
        //行程结束，记录结束时间/位置、里程、各种费用、释放司机锁
        String orderNo = charteredOrderInfoParam.getOrderNo();
        String dateDay = DateUtil.getDateDay();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        QueryWrapper<OaDOrderCharteredDetail> queryWrapper = new QueryWrapper();
        queryWrapper.eq(OaDOrderCharteredDetail.ORDER_NO, orderNo);
        List<OaDOrderCharteredDetail> oaDOrderCharteredDetails = oaDOrderCharterDetailMapper.selectList(queryWrapper);
        int payment = charteredOrderInfoParam.getPaymentType();
        for (int i = 0; i < oaDOrderCharteredDetails.size(); i++) {
            OaDOrderCharteredDetail cd = oaDOrderCharteredDetails.get(i);
            if (sdf.format(cd.getOrderDate()).equals(dateDay)) {
                cd.setStatus(EOrderStatus.paymented.getType());//12
                cd.setTlng(charteredOrderInfoParam.getTlng());
                cd.setTlat(charteredOrderInfoParam.getTlat());
                cd.setEndTime(new Date());
                cd.setExceedDistance(charteredOrderInfoParam.getExceedDistance());
                cd.setExceedDistanceCost(charteredOrderInfoParam.getExceedDistanceCost());
                cd.setExceedTime(charteredOrderInfoParam.getExceedTime());
                cd.setExceedTimeCost(charteredOrderInfoParam.getExceedTimeCost());
                cd.setNormalDistance(charteredOrderInfoParam.getNormalDistance());
                cd.setNormalTime(charteredOrderInfoParam.getNormalTime());
                cd.setOtherCost(charteredOrderInfoParam.getOtherCost());
                cd.setOtherCostDetail(charteredOrderInfoParam.getOtherCostDetail());
                cd.setPaymentType(payment);
                GouldResult gouldResult = GouldMapUtils.verificationEmbargoArea(charteredOrderInfoParam.getTlng(), charteredOrderInfoParam.getTlat());
                String endAddress = gouldResult.getRegeocode().getFormatted_address();
                cd.setEndAddress(endAddress);
                UpdateWrapper<OaDOrderCharteredDetail> updateWrapper = new UpdateWrapper<>();
                updateWrapper.eq(OaDOrderCharteredDetail.ORDER_NO, orderNo);
                updateWrapper.eq(OaDOrderCharteredDetail.ORDER_DATE, dateDay);
                oaDOrderCharterDetailMapper.updateById(cd);

                OaCOrder oaCOrder = common.queryOrderMessage(orderNo);
                OaDOrder oaDOrder = oaDOrderMapper.selectOne(Qw.create().eq(OaDOrder.ORDER_NO, orderNo).
                        eq(OaDOrder.APPOINTMENT_TIME,cd.getOrderDate()));
                if (null==oaDOrder){
                    log.info("未查询到订单：{}",orderNo);
                }
                //oaCOrder.setOrderStatus(EOrderStatus.paymented.getType());
                oaDOrder.setOrderStatus(EOrderStatus.paymented.getType());
                oaDOrderMapper.updateDriverOrderById(new Date(),EOrderStatus.paymented.getType(),oaDOrder.getDriverId(),oaCOrder.getOrderNo(),Long.parseLong(oaDOrder.getUserOrderId()));
                // 删除缓存数据
                redisCommon.remove(RedisPrefixConstant.ORDER_OA_D_ORDER + orderNo);
                //解除司机锁定
                log.info("DRIVER_HISTORY 司机被释放了,司机当前订单号:[{}],当前订单状态:[{}],司机ID:[{}]", orderNo, oaDOrder.getOrderStatus(), driverId);
                common.destinationEmancipationDriver(false, oaDOrder.getDriverId(), orderNo);
                Qd total = Qd.create().add("total", oaDOrder.getDrawFee());
                //到达目的地 , 请发送账单给乘客 并提醒乘客带好随身物品
                total.add("orderStatus", oaDOrder.getOrderStatus()).add("msg", MessageConstant.VOICE_END_TAKING_PASSENGERS);
                OaSysMessage oaSysMessage = new OaSysMessage();
                oaSysMessage.setMessageType(1);
                oaSysMessage.setPushCode(EBillType.COMPLETE_TRIP.getIdenifition());
                oaSysMessage.setMessageContent(MessageConstant.COMPLETE_PROMPT + oaCOrder.getPassengerPhoneSuffix() + MessageConstant.THE_TRIP);
                oaSysMessage.setDriverId(oaCOrder.getDriverId());
                oaSysMessage.setTag(oaCOrder.getTag());
                iOaSysMessageService.saveMessage(oaSysMessage);
            }
        }
        return Rv.wrap();
    }

    /**
     * 结束包车订单
     *
     * @param orderNo
     */
    @Override
    public Rv allCharteredEnd(String orderNo) {
        QueryWrapper<OaDOrderCharteredDetail> queryWrapper = new QueryWrapper();
        queryWrapper.eq(OaDOrderCharteredDetail.ORDER_NO, orderNo);
        List<OaDOrderCharteredDetail> oaDOrderCharteredDetails = oaDOrderCharterDetailMapper.selectList(queryWrapper);
        if (oaDOrderCharteredDetails.size() <= 0) {
            return Rv.wrap(404, "订单不存在", "");
        }
        int completeCount = 0;
        for (int i = 0; i < oaDOrderCharteredDetails.size(); i++) {
            OaDOrderCharteredDetail oaDOrderCharteredDetail = oaDOrderCharteredDetails.get(i);
            if (oaDOrderCharteredDetail.getStatus().equals(EOrderStatus.paymented.getType())) {
                completeCount += 1;
            }
        }
        if (oaDOrderCharteredDetails.size() != completeCount) {
            return Rv.wrap(405, "订单尚未全部完成！", "");
        }
        //更新订单状态
        OaCOrder oaCOrder = common.queryOrderMessage(orderNo);
        List<OaDOrder> oaDOrders = oaDOrderMapper.selectList(Qw.create().eq(OaDOrder.ORDER_NO,orderNo));
        OaCOrderPersonal oaCOrderPersonal = oaCOrderPersonalMapper.selectOne(Qw.create().eq(OaCOrderPersonal.ORDER_NO,orderNo));
        oaCOrderPersonal.setOrderStatus(EOrderStatus.paymented.getType());
        oaCOrder.setOrderStatus(EOrderStatus.paymented.getType());
        if (oaCOrderPersonalMapper.updateById(oaCOrderPersonal)>0) {
            for (int i = 0; i < oaDOrders.size(); i++) {
                OaDOrder oaDOrder = oaDOrders.get(i);
                oaDOrder.setOrderStatus(EOrderStatus.paymented.getType());
                if (this.updateById(oaDOrder) ) {
                    try {
                        QueryWrapper<OaDUserInfo> queryWrapper1 = new QueryWrapper<>();
                        queryWrapper1.select(OaDUserInfo.DRIVER_ID, OaDUserInfo.VERSION, OaDUserInfo.ORDER_QUANTITY_COMPLETED);
                        queryWrapper1.eq(OaDUserInfo.DRIVER_ID, oaDOrder.getDriverId());
                        OaDUserInfo one = dUserInfoService.getOne(queryWrapper1);
                        UpdateWrapper<OaDUserInfo> userInfoUpdateWrapper = new UpdateWrapper<>();
                        userInfoUpdateWrapper.set(OaDUserInfo.ORDER_QUANTITY_COMPLETED, one.getOrderQuantityCompleted() + 1);
                        userInfoUpdateWrapper.set(OaDUserInfo.VERSION, one.getVersion() + 1);
                        userInfoUpdateWrapper.eq(OaDUserInfo.VERSION, one.getVersion());
                        userInfoUpdateWrapper.eq(OaDUserInfo.DRIVER_ID, one.getDriverId());
                        dUserInfoService.update(userInfoUpdateWrapper);
                    } catch (Exception e) {
                        throw DiDiException.create(EDiDiErrorCode.dUserInfoSelectFail);
                    }
                }
            }
        }
        //发送司机账单
        HashMap<Long, OaDBill> billHashMap = new HashMap<>();
        List<OaDBill> oaDBills =new ArrayList<>();
        for (int i = 0; i < oaDOrderCharteredDetails.size(); i++) {
            OaDOrderCharteredDetail oaDOrderCharteredDetail = oaDOrderCharteredDetails.get(i);
            Long driverId = Long.parseLong(oaDOrderCharteredDetail.getDriverId());
            //订单结束只发送套餐内费用
            BigDecimal dayTotalFee = oaDOrderCharteredDetail.getPackageCost();
            OaDBill ob = new OaDBill();
            ob.setDriverId(driverId);
            ob.setOrderNumber(orderNo);
            ob.setBillAmount(dayTotalFee);
            ob.setBillType(0);
            ob.setBillTypeDesc("2");
            ob.setLogonTag(BillConstant.LogonTag);
            ob.setTag(TokenUtil.getTag());
            oaDBills.add(ob);
        }
        for (int i = 0; i <oaDBills.size(); i++) {
            OaDBill oa =oaDBills.get(i);
            log.info("--------------------------------------------------------------------------------");
            log.info("此账单派给司机：{}", oa.getDriverId());
            log.info("--------------------------------------------------------------------------------");
            log.info("ORDER_HISTORY 订单号:[{}],发送包车线上支付账单,调用finance服务保存账单,当前账单内容:[{}]", oa.getOrderNumber(), oa);
            oaDOrderService.saveOaDBill(oa.getDriverId(),orderNo,oa.getBillAmount());
        }
        //通知携程订单完成
        StatusCallbackParam statusCallbackParam = new StatusCallbackParam();
        try {
            statusCallbackParam.setChannel(3);
            statusCallbackParam.setOrder_id(orderNo);
            statusCallbackParam.setOrderTpye(7);
            statusCallbackParam.setStatus(CharteredOrderStatus.orderSucccess.getType());
            Rv rv = iDidiService.statusCallback(statusCallbackParam);
            if (rv.getCode() != EErrorCode.success.getValue()) {
                log.info("CHARTERED_ORDER_HISTORY 订单号:[{}],到达目的地,同步状态失败,进入重试机制,请求参数:[{}],调用滴滴服务返回值:[{}] ", oaCOrder.getOrderNo(), statusCallbackParam, rv);
                producer.sendMsg(statusCallbackParam, MqConstant.STATUS_CALL_BACK_SYNC);
            }
            log.info("CHARTERED_ORDER_HISTORY 订单号:[{}],到达目的地,状态同步成功 参数:[{}],返回值:[{}]", oaCOrder.getOrderNo(), statusCallbackParam, rv);
        } catch (Exception e) {
            log.info("ORDER_HISTORY 订单号:[{}],到达目的地,同步状态失败!,向滴滴同步状态实体类:[{}]", oaCOrder.getOrderNo(), statusCallbackParam);
            e.printStackTrace();
        }

        return Rv.wrap();
    }

    /**
     * 获取费用明细
     *
     * @param orderNo 账单ID
     * @return
     */
    @Override
    public Rv getBillDetails(String orderNo, String appCode) {
        com.xnyzc.lhy.order.entity.mq.OaCOrderPersonal oaCOrderPersonal = oaCOrderPersonalMapper.queryBillDetails(orderNo);
        //com.xnyzc.lhy.order.entity.system.OaSysBillRules oaSysBillRules = this.getDrawRatio(oaCOrderPersonal.getRulesId());
        OaSysBillRule oaSysBillRule = this.getDrawRatio2(oaCOrderPersonal.getRulesId());
        if (StringUtils.isBlank(appCode)) {
            throw PangException.create(EErrorCode.noData);
        }
        String[] systemMessage = appCode.split(":");
        String type = systemMessage[0];
        Integer version = Integer.parseInt(systemMessage[1]);
        Boolean validation = false;
        // 旧版本
        if (type.equals(ESystemType.a.getValue()) && version <= 104) {
            validation = true;
        }
        if (type.equals(ESystemType.b.getValue()) && version <= 100) {
            validation = true;
        }
        Map<String, Object> result = new HashMap<>();
        // 通过版本号判断
        if (validation) {
            result = getFirstStageVersion(oaCOrderPersonal, oaSysBillRule, orderNo);
        } else {
            result = getSecondStageVersion(oaCOrderPersonal, oaSysBillRule, orderNo);
        }

        return Rv.wrap(result);
    }

    public Map<String, Object> getFirstStageVersion(com.xnyzc.lhy.order.entity.mq.OaCOrderPersonal oaCOrderPersonal, OaSysBillRule oaSysBillRules, String orderNo) {
        BigDecimal zero = BigDecimal.valueOf(0.00);
        List<Map<String, String>> mapList = new ArrayList<>();
        if (CheckUtil.objIsNotEmpty(oaCOrderPersonal.getStartFee())) {
            if (oaCOrderPersonal.getStartFee().compareTo(zero) == 1) {
                // 起步价
                Map<String, String> map = new HashMap<>(2);
                if (CheckUtil.objIsNotEmpty(oaSysBillRules)) {
                    if (CheckUtil.objIsNotEmpty(oaSysBillRules.getStartMileage())) {
                        //if (oaSysBillRules.getStartTime() >= 60) {
                        map.put("value", "起步 （" + oaSysBillRules.getStartMileage() + "公里 ");
                        //} else {
                        //    map.put("value", "起步 （" + oaSysBillRules.getStartMileage() + "公里 " + oaSysBillRules.getStartTime() + "分钟）");
                        // }
                    } else {
                        map.put("value", "起步");
                    }
                } else {
                    map.put("value", "起步");
                }
                map.put("label", this.draw2(oaCOrderPersonal.getStartFee(), new BigDecimal(oaSysBillRules.getDrawRatio())) + MessageConstant.MONEY_NAME);
                mapList.add(map);
            }
        }
        if (CheckUtil.objIsNotEmpty(oaCOrderPersonal.getMileageFee())) {
            if (oaCOrderPersonal.getMileageFee().compareTo(zero) == 1) {
                // 里程费用
                Map<String, String> map = new HashMap<>(2);
                if (CheckUtil.objIsNotEmpty(oaCOrderPersonal.getMilageDistance())) {
                    map.put("value", "里程 （" + oaCOrderPersonal.getMilageDistance() + "公里）");
                } else {
                    map.put("value", "里程");
                }
                map.put("label", this.draw2(oaCOrderPersonal.getMileageFee(), new BigDecimal(oaSysBillRules.getDrawRatio())) + MessageConstant.MONEY_NAME);
                mapList.add(map);
            }
        }
        if (CheckUtil.objIsNotEmpty(oaCOrderPersonal.getDurationFee())) {
            if (oaCOrderPersonal.getDurationFee().compareTo(zero) == 1) {
                // 时长费用
                Map<String, String> map = new HashMap<>(2);
                if (CheckUtil.objIsNotEmpty(oaCOrderPersonal.getDurationTime())) {
                    if (oaCOrderPersonal.getDurationTime().compareTo(BigDecimal.valueOf(60)) >= 0) {
                        map.put("value", "时长 （" + oaCOrderPersonal.getDurationTime().divide(BigDecimal.valueOf(60), 2, BigDecimal.ROUND_HALF_UP) + "小时）");
                    } else {
                        map.put("value", "时长 （" + oaCOrderPersonal.getDurationTime() + "分钟）");
                    }
                } else {
                    map.put("value", "时长");
                }
                map.put("label", this.draw2(oaCOrderPersonal.getDurationFee(), new BigDecimal(oaSysBillRules.getDrawRatio())) + MessageConstant.MONEY_NAME);
                mapList.add(map);
            }
        }

        if (CheckUtil.objIsNotEmpty(oaCOrderPersonal.getDistanceFee())) {
            if (oaCOrderPersonal.getDistanceFee().compareTo(zero) == 1) {
                // 远途费
                Map<String, String> map = new HashMap<>(2);
                if (CheckUtil.objIsNotEmpty(oaCOrderPersonal.getEmptyDistance())) {
                    map.put("value", "远途 （" + oaCOrderPersonal.getEmptyDistance() + "公里）");
                } else {
                    map.put("value", "远途");
                }
                map.put("label", this.draw2(oaCOrderPersonal.getDistanceFee(), new BigDecimal(oaSysBillRules.getDrawRatio())) + MessageConstant.MONEY_NAME);
                mapList.add(map);
            }
        }
        QueryWrapper<OaOrderOtherPrice> oaOrderOtherPriceQueryWrapper = new QueryWrapper<>();
        oaOrderOtherPriceQueryWrapper.eq(OaOrderOtherPrice.ORDER_NO, orderNo);
        oaOrderOtherPriceQueryWrapper.select(OaOrderOtherPrice.COST_AMOUNT, OaOrderOtherPrice.COST_TYPE);
        List<OaOrderOtherPrice> oaOrderOtherPrices = oaOrderOtherPriceMapper.selectList(oaOrderOtherPriceQueryWrapper);
        for (OaOrderOtherPrice oaOrderOtherPrice : oaOrderOtherPrices) {
            if (oaOrderOtherPrice.getCostType().equals(EOrderCostType.highSpeedFee.getType())) {
                if (oaOrderOtherPrice.getCostAmount().compareTo(zero) == 1) {
                    Map<String, String> map = new HashMap<>(2);
                    map.put("value", "高速费");
                    map.put("label", oaOrderOtherPrice.getCostAmount().toString());
                    mapList.add(map);
                }
            } else if (oaOrderOtherPrice.getCostType().equals(EOrderCostType.bridgeFee.getType())) {
                if (oaOrderOtherPrice.getCostAmount().compareTo(zero) == 1) {
                    Map<String, String> map = new HashMap<>(2);
                    map.put("value", "过桥费");
                    map.put("label", oaOrderOtherPrice.getCostAmount().toString());
                    mapList.add(map);
                }
            } else if (oaOrderOtherPrice.getCostType().equals(EOrderCostType.parkingFee.getType())) {
                if (oaOrderOtherPrice.getCostAmount().compareTo(zero) == 1) {
                    Map<String, String> map = new HashMap<>(2);
                    map.put("value", "停车费");
                    map.put("label", oaOrderOtherPrice.getCostAmount().toString());
                    mapList.add(map);
                }
            }
        }
        if (CheckUtil.objIsNotEmpty(oaCOrderPersonal.getAwaitFee())) {
            if (oaCOrderPersonal.getAwaitFee().compareTo(zero) == 1) {
                // 等待费
                Map<String, String> map = new HashMap<>(2);
                map.put("value", "等待");
                map.put("label", oaCOrderPersonal.getAwaitFee().toString() + MessageConstant.MONEY_NAME);
                mapList.add(map);
            }
        }
        if (CheckUtil.objIsNotEmpty(oaCOrderPersonal.getServiceFee())) {
            if (oaCOrderPersonal.getServiceFee().compareTo(zero) == 1) {
                // 服务费
                Map<String, String> map = new HashMap<>(2);
                map.put("value", "服务");
                map.put("label", oaCOrderPersonal.getServiceFee().toString() + MessageConstant.MONEY_NAME);
                mapList.add(map);
            }
        }

        if (CheckUtil.objIsNotEmpty(oaCOrderPersonal.getEmptyDrivingFee())) {
            if (oaCOrderPersonal.getEmptyDrivingFee().compareTo(zero) == 1) {
                // 空驶费
                Map<String, String> map = new HashMap<>(2);
                map.put("value", "空驶");
                map.put("label", oaCOrderPersonal.getEmptyDrivingFee().toString() + MessageConstant.MONEY_NAME);
                mapList.add(map);
            }
        }
        List<Map<String, Object>> billSaltDetails = oaDOrderMapper.queryBillSaltDetails(orderNo);
        for (Map<String, Object> map : billSaltDetails) {
            map.put("amount", map.get("amount").toString());
        }
        Map<String, Object> resultMap = new HashMap<>(2);
        resultMap.put("billDetails", mapList);
        resultMap.put("billSaltDetails", billSaltDetails);
        if (CheckUtil.objIsEmpty(oaCOrderPersonal.getDrawFee())) {
            resultMap.put("totalAmount", "");
        } else {
            resultMap.put("totalAmount", oaCOrderPersonal.getDrawFee().toString());
        }
        String carType = oaDOrderMapper.queryCarType(TokenUtil.getTokenUserId());
        if (CheckUtil.strIsEmpty(carType)) {
            resultMap.put("carType", "");
        } else {
            resultMap.put("carType", carType);
        }
        return resultMap;
    }

    public Qd getSecondStageVersion(com.xnyzc.lhy.order.entity.mq.OaCOrderPersonal oaCOrder, OaSysBillRule oaSysBillRules, String orderNo) {
        Qd result = Qd.create();
        BigDecimal totalFee = oaCOrder.getDrawFee();
        if (CheckUtil.objIsEmpty(totalFee)) {
            totalFee = new BigDecimal(0);
        }
        BigDecimal zero = new BigDecimal(0);
        List<OrderBillDetailResults> resultsList = new ArrayList<>();
        if (CheckUtil.objIsNotEmpty(oaCOrder.getStartFee(), oaCOrder.getRulesId()) && oaCOrder.getStartFee().compareTo(zero) == 1) {
            OrderBillDetailResults startFeeResults = new OrderBillDetailResults();
            if (CheckUtil.objIsNotEmpty(oaSysBillRules)) {
                startFeeResults.setIsBlack(1);
                startFeeResults.setName(MessageConstant.START);
                startFeeResults.setMoney("<font color='#333333'>" + this.draw(oaCOrder.getStartFee(), new BigDecimal(oaSysBillRules.getDrawRatio())) + MessageConstant.MONEY_NAME + "</font>");
                resultsList.add(startFeeResults);
                OrderBillDetailResults startFee = new OrderBillDetailResults();
                startFee.setIsBlack(0);
                startFee.setName(MessageConstant.CONTAIN + oaSysBillRules.getStartMileage() + MessageConstant.KILOMETRE);
                startFee.setMoney("");
                resultsList.add(startFee);

            }
        }
        if (CheckUtil.objIsNotEmpty(oaCOrder.getMileageFee(), oaCOrder.getMilageDistance()) && oaCOrder.getMileageFee().compareTo(zero) == 1) {
            if (CheckUtil.objIsNotEmpty(oaSysBillRules)) {
                // 总里程
                BigDecimal sumMileage = oaCOrder.getMilageDistance().add(oaSysBillRules.getStartMileage());
                OrderBillDetailResults mileageFeeResults = new OrderBillDetailResults();
                mileageFeeResults.setIsBlack(1);
                mileageFeeResults.setName(MessageConstant.MILEAGE + "(" + sumMileage + MessageConstant.KILOMETRE + ")");
                mileageFeeResults.setMoney("<font color='#333333'>" + this.draw2(oaCOrder.getMileageFee(), new BigDecimal(oaSysBillRules.getDrawRatio())) + MessageConstant.MONEY_NAME + "</font>");
                resultsList.add(mileageFeeResults);
                OrderBillDetailResults mileage = new OrderBillDetailResults();
                mileage.setIsBlack(0);
                mileage.setName(MessageConstant.START + MessageConstant.MILEAGE + oaSysBillRules.getStartMileage() + MessageConstant.KILOMETRE);
                mileage.setMoney("");
                resultsList.add(mileage);
                OrderBillDetailResults fee = new OrderBillDetailResults();
                fee.setIsBlack(0);
                fee.setName(MessageConstant.CALCULATE_METER + oaCOrder.getMilageDistance() + MessageConstant.KILOMETRE);
                fee.setMoney("<font color='#999999'>" + this.draw2(oaCOrder.getMileageFee(), new BigDecimal(oaSysBillRules.getDrawRatio())) + MessageConstant.MONEY_NAME + "</font>");
                resultsList.add(fee);
            }
        }
        if (CheckUtil.objIsNotEmpty(oaCOrder.getDurationFee(), oaCOrder.getDurationTime()) && oaCOrder.getDurationFee().compareTo(zero) == 1) {
            if (CheckUtil.objIsNotEmpty(oaSysBillRules)) {
                // 总时长
                //BigDecimal sumTime = oaCOrder.getDurationTime().add(new BigDecimal(oaSysBillRules.getStartTime()));
                OrderBillDetailResults durationFeeResults = new OrderBillDetailResults();
                durationFeeResults.setName(MessageConstant.DURATIONFEE + "(" + 0 + MessageConstant.MINUTES + ")");
                durationFeeResults.setMoney("<font color='#333333'>" + this.draw2(oaCOrder.getDurationFee(), new BigDecimal(oaSysBillRules.getDrawRatio())) + MessageConstant.MONEY_NAME + "</font>");
                durationFeeResults.setIsBlack(1);
                resultsList.add(durationFeeResults);
                OrderBillDetailResults duration = new OrderBillDetailResults();
                duration.setIsBlack(0);
                duration.setName(MessageConstant.START + MessageConstant.DURATION + 0 + MessageConstant.MINUTES);
                duration.setMoney("");
                resultsList.add(duration);
                OrderBillDetailResults fee = new OrderBillDetailResults();
                fee.setIsBlack(0);
                fee.setName(MessageConstant.CALCULATE_TIME + oaCOrder.getDurationTime() + MessageConstant.MINUTES);
                fee.setMoney("<font color='#999999'>" + this.draw2(oaCOrder.getDurationFee(), new BigDecimal(oaSysBillRules.getDrawRatio())) + MessageConstant.MONEY_NAME + "</font>");
                resultsList.add(fee);
            }
        }
        if (CheckUtil.objIsNotEmpty(oaCOrder.getDistanceFee(), oaCOrder.getEmptyDistance()) && oaCOrder.getDistanceFee().compareTo(zero) == 1) {
            OrderBillDetailResults distanceFeeResults = new OrderBillDetailResults();
            distanceFeeResults.setIsBlack(1);
            distanceFeeResults.setName(MessageConstant.DISTANT + "(" + oaCOrder.getEmptyDistance() + MessageConstant.KILOMETRE + ")");
            distanceFeeResults.setMoney("<font color='#333333'>" + this.draw(oaCOrder.getDistanceFee(), new BigDecimal(oaSysBillRules.getDrawRatio())) + MessageConstant.MONEY_NAME + "</font>");
            resultsList.add(distanceFeeResults);
        }
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq(OaOrderOtherPrice.ORDER_NO, orderNo);
        List<OaOrderOtherPrice> otherPriceList = oaOrderOtherPriceMapper.selectList(queryWrapper);
        BigDecimal otherPriceSum = new BigDecimal(0);
        if (!otherPriceList.isEmpty()) {
            for (OaOrderOtherPrice o : otherPriceList) {
                if (o.getCostAmount().compareTo(zero) == 1) {
                    otherPriceSum = otherPriceSum.add(o.getCostAmount());
                }
            }
            for (OaOrderOtherPrice o : otherPriceList) {
                if (o.getCostAmount().compareTo(zero) == 1) {
                    OrderBillDetailResults otherPriceResults = new OrderBillDetailResults();
                    otherPriceResults.setIsBlack(1);
                    otherPriceResults.setName(EOrderOtherPrice.findById(o.getCostType()).getValue());
                    otherPriceResults.setMoney("<font color='#999999'>" + o.getCostAmount() + MessageConstant.MONEY_NAME + "</font>");
                    resultsList.add(otherPriceResults);
                }
            }
        }
        String carType = "";
        if (CheckUtil.objIsNotEmpty(oaCOrder.getVehicleType())) {
            carType = EvehicleType.findById(oaCOrder.getVehicleType()).getValue();
        }
        // 退款
        QueryWrapper<OaDBill> billQueryWrapper = new QueryWrapper<>();
        billQueryWrapper.eq(OaDBill.ORDER_NUMBER, orderNo);
        billQueryWrapper.eq(OaDBill.BILL_TYPE_DESC, EBillType.TRAVEL_REFUND.getKey());
        List<OaDBill> billList = oaDBillMapper.selectList(billQueryWrapper);
        if (!billList.isEmpty()) {
            BigDecimal billSum = new BigDecimal(0);
            for (OaDBill bill : billList) {
                billSum = billSum.add(bill.getBillAmount());
            }
            OrderBillDetailResults otherResults = new OrderBillDetailResults();
            otherResults.setIsBlack(1);
            otherResults.setName(EBillType.TRAVEL_REFUND.getDesc());
            otherResults.setMoney("<font color='#3276FF'>" + "-" + billSum + MessageConstant.MONEY_NAME + "</font>");
            resultsList.add(otherResults);
        }
        result = Qd.create()
                .add("totalFee", totalFee)
                .add("carType", carType)
                .add("resultsList", resultsList);
        return result;
    }

    /**
     * 旧的计算抽成
     *
     * @param amount
     * @param draw
     * @return
     */
    @Override
    public String draw(BigDecimal amount, BigDecimal draw) {
        // 抽成比例
        BigDecimal drawRatio = BigDecimal.valueOf(1).subtract(draw);
        // 计算抽成后价格
        BigDecimal newAmount = amount.multiply(drawRatio);
        // 四舍五入价格
        double result = newAmount.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();

        return String.valueOf(result);
    }

    /**
     * 新的计算抽成
     *
     * @param amount
     * @param draw
     * @return
     */
    public String draw2(BigDecimal amount, BigDecimal draw) {
        // 抽成比例
        BigDecimal drawRatio = BigDecimal.valueOf(1).subtract(draw.divide(BigDecimal.valueOf(100), 2, BigDecimal.ROUND_HALF_UP));
        // 计算抽成后价格
        BigDecimal newAmount = amount.multiply(drawRatio);
        // 四舍五入价格
        double result = newAmount.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
        return String.valueOf(result);
    }

    /**
     * 获取首页数据
     *
     * @return
     */
    @Override
    public Rv getHomeDetails() {
        Long driverId = TokenUtil.getTokenUserId();
        List<Map<String, Object>> homeDeatils = oaDOrderMapper.queryHomeDeatils(driverId);

        Map<String, String> resultMap = new HashMap<>();

        for (Map<String, Object> map : homeDeatils) {

            int key = (Integer) map.get("key");

            if (key == 1) {
                resultMap.put("orderAccount", map.get("value").toString());
            } else {
                resultMap.put("orderAccount", "0");
            }

            if (key == 2) {
                resultMap.put("dateAccount", map.get("value").toString());
            } else {
                resultMap.put("dateAccount", "0.0");
            }

            if (key == 3) {
                resultMap.put("billAccount", map.get("value").toString());
            } else {
                resultMap.put("billAccount", "0.00");
            }

        }

        return Rv.wrap(resultMap);
    }

    /**
     * 司机订单整合
     *
     * @param results
     * @param orderNo
     */
    public void getDOrderResults(DOrderDetailsResults results, Long orderNo, String userType, String tag) {
        OaDOrder oaDOrder = getDOrderList(orderNo);
        if (CheckUtil.objIsEmpty(oaDOrder)) {
            throw PangException.create(EErrorCode.noData);
        }
        results.setTotalFee("");
        if (CheckUtil.objIsNotEmpty(oaDOrder.getTotalCost())) {
            results.setTotalFee(String.valueOf(oaDOrder.getTotalCost()));
        }
        results.setIsCarpool(oaDOrder.getIsCarpool());
        results.setIsComment(oaDOrder.getIsComment());
        results.setIsLayout(0);
        results.setStarShowName("");
        String phone = "";
        if (StringUtils.isNotEmpty(oaDOrder.getPassengerPhone())) {
            if (oaDOrder.getPassengerPhone().length() > 4) {
                phone = oaDOrder.getPassengerPhone().substring(oaDOrder.getPassengerPhone().length() - 4, oaDOrder.getPassengerPhone().length());
            }
        }
        results.setPassengerPhone(phone);
        //评价集合
        List mdictResult = new ArrayList();
        ParameterEnum type = ParameterEnum.fromTypeName(String.valueOf(results.getIsComment()));
        switch (type) {
            case ZERO:
                mdictResult = iOaSysCommentService.getComment(userType, tag);
                results.setIsLayout(1);
                break;
            default:
                if (StringUtils.isNotEmpty(results.getStar())) {
                    results.setStarShowName(EStarType.findById(Integer.valueOf(results.getStar())).getValue());
                }
                if (results.getOrderStatus().equals(ParameterEnum.SEVEN.getType()) || results.getOrderStatus().equals(ParameterEnum.TWELVE.getType())) {
                    results.setIsLayout(1);
                }
                break;
        }
        results.setDictMap(mdictResult);
    }

    /**
     * 获取订单状态
     *
     * @return
     */
    private String getOrderStatus(Integer orderStatus, List<OaSysDict> orderDictList) {
        String status = "";
        for (OaSysDict dict : orderDictList) {
            if (orderStatus.equals(Integer.valueOf(dict.getValue()))) {
                status = dict.getLabel();
                break;
            }
        }
        return status;
    }

    /**
     * 查询司机接单表
     *
     * @return
     */
    private OaDOrder getDOrderList(Long orderNo) {
        QueryWrapper<OaDOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(OaDOrder.USER_ORDER_NO, String.valueOf(orderNo));
        OaDOrder oaDOrder = oaDOrderMapper.selectOne(queryWrapper);
        return oaDOrder;
    }

    /**
     * 查询订单评价表
     *
     * @return
     */
    private OaOrderEvaluation getOrderEvaluation(Long orderNoId) {
        QueryWrapper<OaOrderEvaluation> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(OaOrderEvaluation.USER_TYPE, 0);
        queryWrapper.eq(OaOrderEvaluation.ORDER_NO, orderNoId);
        OaOrderEvaluation oaOrderEvaluation = oaOrderEvaluationMapper.selectOne(queryWrapper);
        return oaOrderEvaluation;
    }


    /**
     * 通过orderNo查询审批公务订单
     *
     * @param orderNo 订单号
     * @return
     */
    public OaCOrderApprovalOfficial getOrderApprovalOfficialByOrder(String orderNo) {
        QueryWrapper<OaCOrderApprovalOfficial> wrapper = new QueryWrapper<>();
        wrapper.eq(OaCOrderApprovalOfficial.ORDER_NO, orderNo);
        return oaCOrderApprovalOfficialMapper.selectOne(wrapper);
    }


    /**
     * 通过orderNo查询部门公务订单
     *
     * @param orderNo
     * @return
     */
    private OaCOrderDeptOfficial getOrderDeptByOrderNo(String orderNo) {
        QueryWrapper<OaCOrderDeptOfficial> wrapper = new QueryWrapper<>();
        wrapper.eq(OaCOrderDeptOfficial.ORDER_NO, orderNo);
        return oaCOrderDeptOfficialMapper.selectOne(wrapper);
    }

    /**
     * 通过orderNo查询自费叫车订单
     *
     * @param orderNo
     * @return
     */
    private OaCOrderPersonal getOrderPersonalByOrderNo(String orderNo) {
        QueryWrapper<OaCOrderPersonal> wrapper = new QueryWrapper<>();
        wrapper.eq(OaCOrderPersonal.ORDER_NO, orderNo);
        return oaCOrderPersonalMapper.selectOne(wrapper);
    }

    /**
     * 通过orderNo查询个人公务订单
     *
     * @param orderNo
     * @return
     */
    private OaCOrderPersonalOfficial getOrderPersonalOfficialByOrderNo(String orderNo) {
        QueryWrapper<OaCOrderPersonalOfficial> wrapper = new QueryWrapper<>();
        wrapper.eq(OaCOrderPersonalOfficial.ORDER_NO, orderNo);
        return oaCOrderPersonalOfficialMapper.selectOne(wrapper);
    }

    /**
     * 旧的平台抽成比查询
     *
     * @return
     */
    @Override
    public com.xnyzc.lhy.order.entity.system.OaSysBillRules getDrawRatio(Long rulesId) {

        QueryWrapper<OaSysBillRules> oaSysBillRulesQueryWrapper = new QueryWrapper<>();
        oaSysBillRulesQueryWrapper.eq(OaSysBillRules.RULES_ID, rulesId);
        oaSysBillRulesQueryWrapper.select(OaSysBillRules.DRAW_RATIO, OaSysBillRules.START_MILEAGE);
        com.xnyzc.lhy.order.entity.system.OaSysBillRules oaSysBillRules = oaSysBillRulesMapper.selectOne(oaSysBillRulesQueryWrapper);

        if (CheckUtil.objIsEmpty(oaSysBillRules)) {
            throw PangException.create(EErrorCode.noData);
        }

        return oaSysBillRules;
    }

    /**
     * 新的平台抽成比查询
     *
     * @return
     */
    public OaSysBillRule getDrawRatio2(Long rulesId) {

        QueryWrapper<OaSysBillRule> oaSysBillRulesQueryWrapper = new QueryWrapper<>();
        oaSysBillRulesQueryWrapper.eq(OaSysBillRule.RULE_ID, rulesId);
        oaSysBillRulesQueryWrapper.select(OaSysBillRule.DRAW_RATIO, OaSysBillRule.START_MILEAGE);
        OaSysBillRule oaSysBillRule = oaSysBillRuleMapper.selectOne(oaSysBillRulesQueryWrapper);

        if (CheckUtil.objIsEmpty(oaSysBillRule)) {
            throw PangException.create(EErrorCode.noData);
        }

        return oaSysBillRule;
    }
}
